package com.hrt.datasender.datadao.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.btcode.db.sqlparameter.SQLParameterList;
import com.btcode.orm.executer.IORMExecuter;
import com.hrt.datasender.datadao.model.BdSourceModel;
import com.hrt.db.DBManager;

public final class BdSecondDataService {

    private static volatile BdSecondDataService instance;

    private BdSecondDataService() {

    }

    public static BdSecondDataService getInstance() {
        if (instance == null) {
            synchronized (BdSecondDataService.class) {
                if (instance == null) {
                    instance = new BdSecondDataService();
                }
            }
        }
        return instance;
    }

    /**
     * 获取最新一组数据
     * 
     * @param start
     * @param end
     * @return
     */
    public List<BdSourceModel> getLastSecondData(String tableName, Date start, Date end) {

        IORMExecuter ormExecuter = DBManager.getORMExecuter();

        String datasql = " SELECT * FROM " + tableName
                + " WHERE DATATIME > @start and DATATIME <= @end order by DATATIME DESC ";

        SQLParameterList pc = new SQLParameterList();
        pc.put("start", start);
        pc.put("end", end);

        List<BdSourceModel> models = ormExecuter.getModelListSQL(datasql, pc, BdSourceModel.class);

        if (models == null || models.size() <= 0) {
            return null;
        }

        List<BdSourceModel> result = new ArrayList<>();
        BdSourceModel bdSourceModel = models.get(0);
        result.add(bdSourceModel);

        for (int i = 1; i < models.size(); i++) {
            BdSourceModel m = models.get(i);
            if (m.getDatatime().equals(bdSourceModel.getDatatime())) {
                result.add(m);
            }
        }

        return result;
    }
}